package com.xxxx.server.config.security.config;


import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 * 自定义序列化
 */
public class CustomAuthorityDeserializer extends JsonDeserializer {
    @Override
    public Object deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JacksonException {
        ObjectCodec codec =jsonParser.getCodec();
        JsonNode jsonNode =codec.readTree(jsonParser);
        List<GrantedAuthority> authorityList =new LinkedList<>();
         Iterator iterator =jsonNode.elements();
         while (iterator.hasNext()){
             JsonNode jsonNode1= (JsonNode) iterator.next();
             JsonNode jsonNode2=jsonNode1.get("authority");
             authorityList.add(new SimpleGrantedAuthority(jsonNode2.asText()));
         }
         return authorityList;
    }
}
